package com.boang.controller.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.boang.entity.SysUser;
import com.boang.service.SysUserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@Tag(name = "Excel导出")
@RestController
@RequestMapping("/excel")
public class ExcelExportController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/export/users")
    public void exportUserList(HttpServletResponse response) throws IOException {
        // 1. 准备数据（实际应从数据库获取）
        List<SysUser> dataList = sysUserService.list();

        // 2. 设置响应头
        String fileName = URLEncoder.encode("用户列表", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 3. 写入Excel
        EasyExcel.write(response.getOutputStream(), SysUser.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("用户数据")
                .doWrite(dataList);
    }


}